package com.flute.framework.autoprompt;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.flute.tools.util.PinyinUtil;
import com.flute.tools.util.StringUtil;

public class CommonPriorityStrategy implements IPriorityStrategy {
	private int priorityLength;

	public CommonPriorityStrategy() {
	}

	public CommonPriorityStrategy(int length) {
		this.priorityLength = length;
	}

	@Override
	public List<TrainningToken> getWordResult(String string) {
		string = StringUtil.getStandardString(string);
		List<TrainningToken> tokenList = new ArrayList<TrainningToken>();
		HashSet<String> pSet = new HashSet<String>();

		// 完全一样
		if (StringUtil.containsEnglishOrNumber(string)) {
			addString(tokenList, string, pSet, string, 10, Math.min(15, string
					.length() - 1));
			String standardString = SpecialChars.getStatndardString(string);
			if (!string.equals(standardString)) {
				addString(tokenList, standardString, pSet, string, 10, Math
						.min(15, standardString.length() - 1));
			}
		} else {
			addString(tokenList, string, pSet, string, 10, Math.min(12, string
					.length() - 1));
			String standardString = SpecialChars.getStatndardString(string);
			if (!string.equals(standardString)) {
				addString(tokenList, standardString, pSet, string, 10, Math
						.min(12, standardString.length() - 1));
			}
		}

		if (StringUtil.containsChinese(string)) {

			// 拼音
			String[] pinyins = PinyinUtil.getPinyinStrings(string.trim());
			for (String pinyin : pinyins) {
				addString(tokenList, pinyin, pSet, string, 9, Math.min(15,
						pinyin.length()));
			}

			// 拼音首字母
			pinyins = PinyinUtil.getPinyinHeaders(string.trim());
			for (String pinyin : pinyins) {
				addString(tokenList, pinyin, pSet, string, 8, Math.min(10,
						pinyin.length()));
			}
		}

		return tokenList;
	}

	private void addString(List<TrainningToken> list, String text,
			HashSet<String> pSet, String originalText, double priority,
			int length) {
		Token t = new Token(priorityLength);
		t.setOriginalText(originalText);
		t.updatePriority(priority, 1);

		for (int i = 1; i <= length; i++) {
			String subText = text.substring(0, i);
			if (!pSet.contains(subText)) {
				pSet.add(subText);

				TrainningToken token = new TrainningToken();
				token.setText(subText);
				token.setToken(t);

				list.add(token);
			}
		}
	}

	public int getPriorityLength() {
		return priorityLength;
	}

	public void setPriorityLength(int priorityLength) {
		this.priorityLength = priorityLength;
	}
}
